package com.powernode.strategy.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.powernode.constant.AuthConstants;
import com.powernode.domain.LoginSysUser;
import com.powernode.mapper.LoginSysUserMapper;
import com.powernode.model.SecurityUser;
import com.powernode.strategy.LoginStrategy;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Set;

/**
 * @Author 梁卓
 * @Version 1.0
 * @ClassName SysUserLoginStrategy
 * @Description 商城后台管理系统登录策略的具体实现
 * @Date 2024/07/20 23:28
 */
@Service(AuthConstants.SYS_USER_LOGIN)
public class SysUserLoginStrategy implements LoginStrategy {

    @Resource
    private LoginSysUserMapper loginSysUserMapper;

    @Override
    public UserDetails realLogin(String username) {
        LoginSysUser loginSysUser = loginSysUserMapper.selectOne(
                new LambdaQueryWrapper<LoginSysUser>()
                        .eq(LoginSysUser::getUsername, username)
        );
        if(ObjectUtil.isNotNull(loginSysUser)) {
            // 查询权限集合（set 不可重复）达到去重的效果
            Set<String> perms = loginSysUserMapper.selectPermsByUserId(loginSysUser.getUserId());
            SecurityUser securityUser = new SecurityUser();
            securityUser.setUserId(loginSysUser.getUserId());
            securityUser.setUsername(loginSysUser.getUsername());
            securityUser.setPassword(loginSysUser.getPassword());
            securityUser.setShopId(loginSysUser.getShopId());
            securityUser.setStatus(loginSysUser.getStatus());
            securityUser.setLoginType(AuthConstants.SYS_USER_LOGIN);
            securityUser.setPerms(perms);
            return securityUser;
        }
        return null;
    }
}
